package com.ruoyi.web.exams.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.web.exams.domain.*;
import com.ruoyi.web.exams.dto.UserExamPagerDto;
import com.ruoyi.web.exams.mapper.*;
import com.ruoyi.web.exams.service.IExamPagerService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 试卷Service业务层处理
 *
 * @author ruoyi
 * @date 2024-10-02
 */
@Service
public class ExamPagerServiceImpl extends ServiceImpl<ExamPagerMapper, ExamPager> implements IExamPagerService {

    @Resource
    private ExamPagerMapper examPagerMapper;
    @Resource
    private ExamQuestionMapper examQuestionMapper;
    @Resource
    private ExamAnswersMapper examAnswersMapper;
    @Resource
    private ExamResultMapper examResultMapper;
    @Resource
    private ExamOptionMapper examOptionMapper;

    /**
     * 查询试卷
     *
     * @param id 试卷主键
     * @return 试卷
     */
    @Override
    public ExamPager selectExamPagerById(Long id) {
        return examPagerMapper.selectExamPagerById(id);
    }

    /**
     * 查询试卷列表
     *
     * @param examPager 试卷
     * @return 试卷
     */
    @Override
    public List<ExamPager> selectExamPagerList(ExamPager examPager) {
        return examPagerMapper.selectExamPagerList(examPager);
    }

    /**
     * 新增试卷
     *
     * @param examPager 试卷
     * @return 结果
     */
    @Override
    public int insertExamPager(ExamPager examPager) {
        examPager.setCreateTime(DateUtils.getNowDate());
        return examPagerMapper.insertExamPager(examPager);
    }

    /**
     * 修改试卷
     *
     * @param examPager 试卷
     * @return 结果
     */
    @Override
    public int updateExamPager(ExamPager examPager) {
        examPager.setUpdateTime(DateUtils.getNowDate());
        return examPagerMapper.updateExamPager(examPager);
    }

    /**
     * 批量删除试卷
     *
     * @param ids 需要删除的试卷主键
     * @return 结果
     */
    @Override
    public int deleteExamPagerByIds(Long[] ids) {
        return examPagerMapper.deleteExamPagerByIds(ids);
    }

    /**
     * 删除试卷信息
     *
     * @param id 试卷主键
     * @return 结果
     */
    @Override
    public int deleteExamPagerById(Long id) {
        return examPagerMapper.deleteExamPagerById(id);
    }

    @Override
    public UserExamPagerDto startPager(Long pagerId) {
        Long userId = SecurityUtils.getUserId();
        UserExamPagerDto userExamPagerDto = new UserExamPagerDto();
        List<ExamQuestion> questions = examQuestionMapper.queryPagerQuestions(pagerId);
        userExamPagerDto.setQuestions(questions);
        //将选项插入题目
        List<Long> questionIds = questions.stream().map(ExamQuestion::getId).collect(Collectors.toList());
        List<ExamOption> examOptions = examOptionMapper.selectList(new LambdaQueryWrapper<ExamOption>()
                .in(ExamOption::getQuestionId, questionIds));
        for (ExamQuestion examQuestion : questions) {
            List<ExamOption> options = new ArrayList<>();
            for (ExamOption examOption : examOptions) {
                if (examOption.getQuestionId().longValue() == examQuestion.getId().longValue()) {
                    options.add(examOption);
                }
            }
            examQuestion.setOptions(options.stream().sorted().collect(Collectors.toList()));
        }
        //根据试卷ID,人ID查询答题结果,检查答题结果是否存在未完成的,有则返回此答题数据,无则新建答题数据
        ExamPager examPager = examPagerMapper.selectById(pagerId);
        userExamPagerDto.setExamPager(examPager);
        //查答题结果概况
        ExamResult examResult = examResultMapper.selectOne(new LambdaQueryWrapper<ExamResult>()
                .eq(ExamResult::getPagerId  , examPager.getId())
                .eq(ExamResult::getPersonalId  , userId)
                .eq(ExamResult::getIsFinish  , false));

        if (examResult == null) {
            //没有未完成的答题记录,新建一个
            ExamResult examResultAdd = new ExamResult();
            examResultAdd.setPagerId(examPager.getId());
            examResultAdd.setPersonalId(userId);
            examResultAdd.setStartTime(new Date());
            examResultAdd.setIsFinish(false);
            examResultAdd.setTotalScore(examPager.getPagerScore());
            examResultMapper.insert(examResultAdd);
            userExamPagerDto.setExamResult(examResultAdd);
            for (ExamQuestion question : questions) {
                ExamAnswers examAnswers = new ExamAnswers();
                examAnswers.setPagerId(pagerId);
                examAnswers.setQuestionId(question.getId());
                examAnswers.setUserId(userId);
                examAnswers.setQuestionType(question.getQuestionType());
                switch (question.getQuestionType().intValue()) {
                    case 1:
                        examAnswers.setScoreNumber(examPager.getSingleQuestionScore());
                        break;
                    case 2:
                        examAnswers.setScoreNumber(examPager.getMultiQuestionScore());
                        break;
                    case 3:
                        examAnswers.setScoreNumber(examPager.getJudgeQuestionScore());
                        break;
                    default:
                        break;
                }
                examAnswers.setExamResultId(examResultAdd.getId());
                examAnswersMapper.insert(examAnswers);
                question.setExamAnswers(examAnswers);
            }
        } else {
            userExamPagerDto.setExamResult(examResult);
            //查答题结果列表
            List<ExamAnswers> answers = examAnswersMapper.selectList(new LambdaQueryWrapper<ExamAnswers>()
                    .eq(ExamAnswers::getExamResultId  , examResult.getId()));
//        userExamPagerDto.setExamAnswers(answers);
            for (ExamQuestion question : questions) {
                answers.forEach(examAnswers -> {
                    if (question.getId().longValue() == examAnswers.getQuestionId()) {
                        question.setExamAnswers(examAnswers);
                    }
                });
            }
        }
        return userExamPagerDto;
    }

}